// 获取网络时间
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <errno.h>
#include <stdint.h>

#define NTP_SERVER "ntp.aliyun.com"
#define NTP_PORT 123
#define NTP_PACKET_SIZE 48
#define NTP_TIMESTAMP_DELTA 2208988800ull

void get_ntp_time(char *time_str, size_t buffer_size) {
    int sockfd;
    struct sockaddr_in serv_addr;
    char packet[NTP_PACKET_SIZE] = {0};
    time_t ntp_time;

    // 创建 UDP socket
    sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (sockfd < 0) {
        perror("socket");
        strcpy(time_str, "Socket error");
        return;
    }

    // 设置超时（3秒）
    struct timeval timeout = {3, 0};
    setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));

    // 设置 NTP 服务器地址
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(NTP_PORT);
    
    // 解析NTP服务器地址
    struct hostent *host = gethostbyname(NTP_SERVER);
    if (host == NULL) {
        herror("gethostbyname");
        close(sockfd);
        strcpy(time_str, "DNS resolution failed");
        return;
    }
    memcpy(&serv_addr.sin_addr, host->h_addr_list[0], host->h_length);

    // 构造 NTP 请求包
    packet[0] = 0x1B;  // LI=0, VN=3, Mode=3 (Client)

    // 发送请求
    if (sendto(sockfd, packet, NTP_PACKET_SIZE, 0, 
              (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
        perror("sendto");
        close(sockfd);
        strcpy(time_str, "Send failed");
        return;
    }

    // 接收响应
    socklen_t addr_len = sizeof(serv_addr);
    if (recvfrom(sockfd, packet, NTP_PACKET_SIZE, 0, 
                (struct sockaddr *)&serv_addr, &addr_len) < 0) {
        perror("recvfrom");
        close(sockfd);
        strcpy(time_str, "Receive failed");
        return;
    }

    // 解析 NTP 时间戳（从第32字节开始，8字节）
    uint32_t seconds_since_1900 = ntohl(*(uint32_t *)(packet + 32));
    ntp_time = (time_t)seconds_since_1900 - NTP_TIMESTAMP_DELTA;

    // 转换为本地时间字符串
    struct tm *timeinfo = localtime(&ntp_time);
    strftime(time_str, buffer_size, "%Y-%m-%d %H:%M:%S", timeinfo);

    close(sockfd);
}

int main() {
    char time_str[64];
    
    // 添加循环，每秒更新一次
    while (1) {
        get_ntp_time(time_str, sizeof(time_str));
        printf("\r时间：%s",  time_str);
        fflush(stdout);  // 刷新输出缓冲区，确保立即显示
        
        sleep(1);  // 等待1秒
    }

    return 0;
}